package com.colin.aiyi.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaDataSource;
import android.media.MediaPlayer;
import android.net.Network;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.webkit.URLUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by hl on 2017/5/10.
 *
 */

public class MusicUtil implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener{
    private static MusicUtil mMediaPlayUtil;
    public static final int MEDIA_STATUS_START = 0;
    public static final int MEDIA_STATUS_PREPARE=1;
    public static final int MEDIA_STATUS_PLAY = 2;
    public static final int MEDIA_STATUS_STOP = 3;
    public static final int MEDIA_STATUS_PAUSE = 4;
    public static final int MEDIA_STATUS_COMLETION=5;
    public static final int MEDIA_STATUS_EEROR=6;
    private  MediaPlayer mMediaPlayer;
    private int media_player_status;
    private boolean AutoPlay=true;
    private Thread thread;
    private boolean isPlay=false;
    private String musicPic;
    private String musicTitle;

    public String getMusicTitle() {
        return musicTitle;
    }

    public void setMusicTitle(String musicTitle) {
        this.musicTitle = musicTitle;
    }

    public String getMusicPic() {
        return musicPic==null?"":musicPic;
    }

    public void setMusicPic(String musicPic) {
        this.musicPic = musicPic;
    }

    public boolean isAutoPlay() {
        return AutoPlay;
    }

    public void setAutoPlay(boolean autoPlay) {
        AutoPlay = autoPlay;
    }

    /*资源准备完成开启 开放播放功能*/
    @Override
    public void onPrepared(MediaPlayer mp) {
        media_player_status=MEDIA_STATUS_PREPARE;
        if (isAutoPlay())
        {
            mMediaPlayer.start();
            isPlay=true;
            updateProgress();
            media_player_status=MEDIA_STATUS_PLAY;
        }
        EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mp));

    }
    @Override
    public void onCompletion(MediaPlayer mp) {
        media_player_status=MEDIA_STATUS_COMLETION;
        isPlay=false;
        updateProgress();
        EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mp));
    }

    private void updateProgress(){
        TimerTask task= new TimerTask() {
            @Override
            public void run() {
                if (isPlay)
                    EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
            }
        };
        new Timer().schedule(task, 5,1000);
    }


    public static MusicUtil getInstance(){
        if(mMediaPlayUtil == null){
            mMediaPlayUtil = new MusicUtil();
        }
        return  mMediaPlayUtil;
    }

    private MusicUtil() {
      create();
    }

    public void play(){
        if (media_player_status==MEDIA_STATUS_PLAY)
        {
            pause();
            return;
        }
        try {
            if (media_player_status==MEDIA_STATUS_PREPARE||media_player_status==MEDIA_STATUS_PAUSE)
            {
                mMediaPlayer.start();
                updateProgress();
                isPlay=true;
                media_player_status=MEDIA_STATUS_PLAY;
            }
        }catch (Exception e){
            e.printStackTrace();
            media_player_status=MEDIA_STATUS_EEROR;
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));

        }
    }


    /*********
     * 控制播放进度
     * @param msec
     */
    public void pause(int msec){
        if(mMediaPlayer != null&&(media_player_status==MEDIA_STATUS_PLAY||media_player_status==MEDIA_STATUS_PREPARE)){
            try {
                mMediaPlayer.seekTo(msec);
                mMediaPlayer.start();
                updateProgress();
                isPlay=true;
                media_player_status=MEDIA_STATUS_PLAY;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    public void pause(){
        if(mMediaPlayer != null){
            try {
                mMediaPlayer.pause();
                media_player_status=MEDIA_STATUS_PAUSE;
                isPlay=false;
                EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }


    public void stop(){
        if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
            isPlay=false;
            media_player_status=MEDIA_STATUS_STOP;
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
        }
        sendStopEvent();
    }




    public int getCurrentPosition(){
        if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
            return mMediaPlayer.getCurrentPosition();
        }else{
            return 0;
        }
    }


    public int getDutation(){
        if(mMediaPlayer!= null && mMediaPlayer.isPlaying()){
            return mMediaPlayer.getDuration();
        }else{
            return 0;
        }
    }


    public boolean isPlaying(){
        if(mMediaPlayer != null){
            return mMediaPlayer.isPlaying();
        }else{
            return false;
        }
    }

    public boolean isPause(){
        if (media_player_status==MEDIA_STATUS_PAUSE){
            return true;
        }else {
            return false;
        }
    }


    public void create( ) {
        if (mMediaPlayer!=null)
        {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer=null;
        }
        mMediaPlayer =  new MediaPlayer();
      //  EventBus.getDefault().register(this);

    }

    private String getPathFromUri(Uri songUri){
        try {
            return URLDecoder.decode(songUri.getPath().toString(), "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setDataSource(AssetFileDescriptor afd){
        reserMediaPlay();
        try {
            mMediaPlayer.setDataSource(afd);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            media_player_status=MEDIA_STATUS_EEROR;
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
        }
    }

    public void setDataSource(Context context,Uri uri){
        reserMediaPlay();
        try {
            mMediaPlayer.setDataSource(context,uri);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        media_player_status=MEDIA_STATUS_START;
        isPlay=false;
        EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));


    }
    public void setDataSource(Context context,String path)
    {
        if (path==null)
        {
            media_player_status=MEDIA_STATUS_EEROR;
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
            return;
        }
        if (URLUtil.isNetworkUrl(path)) {
            setDataSource(context,Uri.parse(path));
            return;
        }
        setDataSource(path);
    }
    public void setDataSource(String path){
        reserMediaPlay();
        try {
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
            media_player_status=MEDIA_STATUS_EEROR;
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
        }
    }
    public void setDataSource(FileDescriptor fileDescriptor){
        reserMediaPlay();
        try {
            mMediaPlayer.setDataSource(fileDescriptor);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            EventBus.getDefault().post(new MusicUtil.MuiscEvent(media_player_status,mMediaPlayer));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setDataSource(MediaDataSource mediaDataSource){
        reserMediaPlay();
        mMediaPlayer.setDataSource(mediaDataSource);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepareAsync();
    }
    private void reserMediaPlay(){
//        if (mMediaPlayer==null)
//            create();
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
        mMediaPlayer.release();
        mMediaPlayer=null;
        mMediaPlayer=new MediaPlayer();
        media_player_status=MEDIA_STATUS_START;
    }

    public void sendStartEvent(){
        EventBus.getDefault().post(new MusicUtil.MuiscEvent(MEDIA_STATUS_START,mMediaPlayer));
    }

    public void sendStopEvent(){
        EventBus.getDefault().post(new MusicUtil.MuiscEvent(MEDIA_STATUS_STOP,mMediaPlayer));
    }



    public class MuiscEvent {
        int eventType;
        MediaPlayer mediaPlayer;

        public MuiscEvent(int eventType, MediaPlayer mediaPlayer) {
            this.eventType = eventType;
            this.mediaPlayer = mediaPlayer;
        }

        public int getEventType() {
            return eventType;
        }

        public void setEventType(int eventType) {
            this.eventType = eventType;
        }

        public MediaPlayer getMediaPlayer() {
            return mediaPlayer;
        }

        public void setMediaPlayer(MediaPlayer mediaPlayer) {
            this.mediaPlayer = mediaPlayer;
        }
    }


    public static  int  getPlayProress(int proredss,int count){
        return proredss*100/count;
    }

    public static  String getMusicTime(int time) {
        int musicTime = time / 1000;
        return musicTime / 60 + ":" + musicTime % 60;
    }

    public static  String getC(int time) {
        int musicTime = time / 1000;
        return musicTime / 60 + ":" + musicTime % 60;
    }

}



